<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>第十二节课</title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			.container {
				width: 100vw;
				height: 100vh;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			canvas {
				width: 500px;
				height: 500px;
				border: 1px solid #333333;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<canvas id="canvas" width="500" height="500"></canvas>
			<input type="button" value="补充子弹" id="zd" />
			<p id="zdgs"></p>
		</div>
	</body>
	<script>
		window.onload = function() {
			let oCanvas = document.getElementById('canvas');
			let yPen = oCanvas.getContext("2d");
			yPen.fillRect(0, 200, 100, 100);

			let a = 80;
			let i = 0;
			let t = 0;
			let g = 0;
			let q = 5;
			let o = 0;
			let zd = document.getElementById('zd');
			zd.onclick = function() {
				q = q + 5;
				console.dir();
				document.getElementById("zdgs").innerText = "子弹剩余：" + q
			}
			document.getElementById("zdgs").innerText = "子弹剩余：" + q
			let time
			document.onkeypress = function(e) {
				if (i == 0) {
					if (e.keyCode == 32) {
						if (o == 0 && q != 0) {
							g = g + 1;
							q--;
							o = 1;
						}
						time = setInterval(() => {
							xxx()
						}, 500);
						i = 1;
						console.dir(q);
						document.getElementById("zdgs").innerText = "子弹剩余：" + q
					}
				}
			}
			yPen.fillRect(a, 240, 10, 10);

			function xxx() {
				let step = 30;
				if (i == 1) {
					if (a > 80) {
						yPen.clearRect(a, 240, 10, 10);
					}
					a = a + step;
					yPen.translate(step, 0);

					yPen.fillRect(a, 240, 10, 10);
					t = t + step
					if (a == 320) {
						clearInterval(time);
						yPen.translate(-t, 0)
						t = 0;
						a = 80;
						g = g - 1;
					}
					if (g == 0) {
						i--;
						o = 0;
					}
				}
				if (g == 0 && q == 0) {
					alert('请补充弹药');
					q = q + 5;
					document.getElementById("zdgs").innerText = "子弹剩余：" + q
				}
				console.dir(g);
			}
		}
	</script>
</html>
